package com.sam;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.api.client.auth.oauth.OAuthHmacSigner;
import com.google.api.client.auth.oauth.OAuthParameters;
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.appengine.auth.oauth2.AbstractAppEngineAuthorizationCodeServlet;
import com.google.api.client.extensions.appengine.auth.oauth2.AppEngineCredentialStore;
import com.google.api.client.extensions.appengine.http.UrlFetchTransport;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.services.GoogleClient;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpMethod;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpClient;
import com.google.api.client.http.json.JsonHttpRequest;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.appengine.api.users.UserServiceFactory;

public class GmailAppEngine extends AbstractAppEngineAuthorizationCodeServlet {

	  /**
	 * 
	 */
	private static final long serialVersionUID = -6936469887500546786L;
	
	private static final Logger log = Logger.getLogger(GmailAppEngine.class.getName());
	
	// O7Mt34OnIGAHrIZTd1MFTbNf
	// mycrazymula.com.ar

	@Override
	  protected void doGet(HttpServletRequest request, HttpServletResponse response)
	      throws IOException {
		
		List<String> scope = new ArrayList<String>();
		scope.add("https://mail.google.com/mail/feed/atom");
		//scope.add("https://apps-apis.google.com/a/feeds/emailsettings/2.0/");
		
		String userId = UserServiceFactory.getUserService().getCurrentUser().getUserId();
		
		GoogleAuthorizationCodeFlow googleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow.Builder(new UrlFetchTransport(), new JacksonFactory(),
				  "446717159838-t9qnn8kpjjqega908vdbdguro25cmk9p.apps.googleusercontent.com", "txpMAz9_7L7vSQ4UJclVTZi3",
			        scope).setCredentialStore(
			        new AppEngineCredentialStore()).build();
		
		
		Credential credential = googleAuthorizationCodeFlow.loadCredential(userId);
		
		URL url = new URL("https://mail.google.com/mail/feed/atom/");
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.addRequestProperty("Authorization",  "Bearer "  + credential.getAccessToken());
		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		String line;
		
		PrintWriter writer = response.getWriter();
		
		writer.println("<html><body>");
		writer.println("<textarea cols='180' rows='25'>");
		while ((line = reader.readLine()) != null) {
			System.out.println(line);
			writer.println(line);
		}
		reader.close();
		writer.println("</textarea> ");
		
		
		HttpTransport httpTransport = new NetHttpTransport();
		JacksonFactory jsonFactory = new JacksonFactory();
		
		// The 2-LO authorization section
		OAuthHmacSigner signer = new OAuthHmacSigner();
		signer.clientSharedSecret = "O7Mt34OnIGAHrIZTd1MFTbNf";
		
		OAuthParameters oauthParameters = new OAuthParameters();
		oauthParameters.version = "2.0";
		oauthParameters.consumerKey = "mycrazymula.com.ar";
		oauthParameters.signer = signer;
		
		String[] split = UserServiceFactory.getUserService().getCurrentUser().getEmail().split("@");
	
		GoogleClient.Builder builder = new GoogleClient.Builder(httpTransport, jsonFactory, "https://apps-apis.google.com/", "a/feeds/emailsettings/2.0/", oauthParameters);
		JsonHttpClient build = builder.setApplicationName("fdsf").build();
		
		
		JsonHttpRequest jsonHttpRequest = new JsonHttpRequest(build, HttpMethod.GET, split[1] + "/" + split[0] + "/label/", null);
		
		jsonHttpRequest.getUnknownKeys().put("xoauth_requestor_id", "martinrico@mycrazymula.com.ar");
		jsonHttpRequest.getUnknownKeys().put("key", "AIzaSyBJwUVfurVheN7_oJy4vBOGNKqqAIZuj-k");
		
		HttpResponse executeUnparsed = jsonHttpRequest.executeUnparsed();
		writer.println("<textarea cols='180' rows='25'>");
		writer.println(executeUnparsed.parseAsString());
		writer.println("</textarea> ");		
		writer.println("</body></html>");
	  }

	  @Override
	  protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
	    GenericUrl url = new GenericUrl(req.getRequestURL().toString());
	    url.setRawPath("/oauth2callback");
	    return url.build();
	  }

	  @Override
	  protected AuthorizationCodeFlow initializeFlow() throws IOException {
		  List<String> scope = new ArrayList<String>();
		  scope.add("https://mail.google.com/mail/feed/atom");
		 // scope.add("https://apps-apis.google.com/a/feeds/emailsettings/2.0/");
		  return new GoogleAuthorizationCodeFlow.Builder(new UrlFetchTransport(), new JacksonFactory(),
			        "446717159838-t9qnn8kpjjqega908vdbdguro25cmk9p.apps.googleusercontent.com", "txpMAz9_7L7vSQ4UJclVTZi3",
			        scope).setCredentialStore(
			        new AppEngineCredentialStore()).build();   
	  }
	  
	  
	  
	  
	}